package com.fyzk.activity.news;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseFragment;
import com.fyzk.activity.app.AppToast;
import com.fyzk.net.Commands;
import com.tyjc.lottery.R;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.RefreshListView;

import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import com.wf.domain.UrlDef;
import http.XRequestCallBack;

/**
 * Created by fanxs11 on 17/4/21.
 */

public class NewsListFragment extends BaseFragment implements RefreshListView.OnRefreshListener {

    private final String TAG = this.getClass().getSimpleName();

    private RefreshListView listView;
    private NewsListAdapter adapter;
    private int page = 1;
    private int count = 20;
    private boolean requestType = false;    //请求方式：true加载更多，false首次请求或刷新

    private boolean isFirst = false;    // 是否是第一进入


    private List<NewsListBean.DataBean> infos = new ArrayList<>();
    private NewsTypeListBean.CategoryBean newsTypeInfo;

    View mainView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isFirst = true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        if (mainView == null) {
            mainView = inflater.inflate(R.layout.fragment_news_list, null);
        }

        if (isFirst) {
            init();
            net();
        }
        isFirst = false;
        return mainView;
    }

    /**
     * 获取新闻列表
     */
    protected void requestNewsList() {
        // TODO Auto-generated method stub

        RequestParams params = new RequestParams(UrlDef.NEWS_URL + Commands.NEWSLIST);
        params.addBodyParameter("category", newsTypeInfo.getNickname());
        params.addBodyParameter("src", "src1");
        params.addBodyParameter("page", page+"");
        params.addBodyParameter("perpage", count+"");
        params.addBodyParameter("iscontent", "0");
        sendRequest(HttpMethod.GET, 1, params, true);
    }

    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param method
     * @param params
     * @param showProgress
     */
    public void sendRequest(HttpMethod method, int requestCode, RequestParams params, final boolean showProgress) {


        if (!AppUtil.isNetworkAvailable(getActivity())) {
            AppToast.getToast().show("网络错误!");
            return;
        }

        if (showProgress) {
//			showProgressDialog();
        }

        XRequestCallBack<String> callBack = new XRequestCallBack<String>(
                requestCode) {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
//                onFailure(getRequestCode(), "网络异常");
                LogUtil.d("请求失败");
                if (!requestType) { // 下拉刷新或第一次请求
                    infos.clear();

                } else {    // 加载更多
                    listView.noMore();

                }
                adapter.setInfos(infos);
                if (showProgress) {
//					cancelProgressDialog();
                }
            }

            @Override
            public void onSuccess(String result) {
                LogUtil.d("联网返回成功："+result);
                super.onSuccess(result);
                NewsListFragment.this.onSuccess(getRequestCode(),
                        result);
                if (showProgress) {
//					cancelProgressDialog();
                }

            }
        };

        LogUtil.v("联网请求：" + params);
        if (method == HttpMethod.POST) {
            x.http().post(params, callBack);
        } else if (method == HttpMethod.GET) {
            x.http().get(params, callBack);
        } else {
            x.http().post(params, callBack);
        }

    }


    protected void onSuccess(int requestCode, String result) {
        NewsListBean newsList = JSON.parseObject(result, NewsListBean.class);
        String status = newsList.getStatus();

        if (status.equals("200")) {

            if (requestType) {  // 加载更多
                if (newsList.getData().size() > 0) {
                    infos.addAll(newsList.getData());
                    listView.hideFooterView();
                } else {
                    listView.noMore();
                }
            } else {
                infos = newsList.getData();
                listView.hideHeaderView();
                if (infos.size() == 0) {
                    listView.noMore();
                }
            }
            adapter.setInfos(infos);
            requestType = false;
        } else {

        }
    }

    private void net() {
        requestNewsList();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    protected void init() {

        Bundle bundle = getArguments();
        if (bundle == null)
            return;
        newsTypeInfo = (NewsTypeListBean.CategoryBean) bundle.getSerializable("info");
        listView = (RefreshListView) mainView.findViewById(R.id.news_listview);
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setOnRefreshListener(this);
        adapter = new NewsListAdapter(getContext());
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (listView.isDownPull){
                    return;
                }
                if (i > 0 && i <= infos.size()) {
                    LogUtil.d("点击item : "+i);
//                    if (infos.get(i-1).getStatus().equals(""+STATUS_NOUSER)){
//                        Intent intent = new Intent(getContext(), CouponDetail.class);
//                        intent.putExtra("coupon", infos.get(i-1));
//                        startActivity(intent);
//                    }
                    Intent intent = new Intent(getContext(),
                            NewsDetailActivity.class);
                    intent.putExtra("info", infos.get(i-1));
                    startActivity(intent);
                }


            }
        });
    }

    public Context getContext() {
        return getActivity();
    }

    @Override
    public void onLeftClick() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onCenterClick() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onRightClick() {
        // TODO Auto-generated method stub
        net();
    }


    @Override
    public void onRight2Click() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onDownPullRefresh() {
        page = 1;
        requestType = false;
        net();
    }

    @Override
    public void onLoadingMore() {
        requestType = true;
        page++;
        net();
    }
}
